package com.yima.baseproj.config.mybatis.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.util.Date;

/**
 * @Author 一码
 * @createDate 2023/4/1 09:00
 * @contact 1424529270@qq.com
 */
@Slf4j
public class MybatisDateTypeHandler implements TypeHandler<Date> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
        if(date == null){
            preparedStatement.setTimestamp(i, Timestamp.valueOf(LocalDateTimeUtil.of(DateUtil.date())));
        }else{
            preparedStatement.setTimestamp(i, Timestamp.valueOf(LocalDateTimeUtil.of(date)));
        }
    }

    @Override
    public Date getResult(ResultSet resultSet, String s) throws SQLException {
        log.info("getResult:{}",s);
        if(resultSet.getTimestamp(s) == null){
            return null;
        }else{
            return DateUtil.parse(DateUtil.format(DateUtil.date(resultSet.getTimestamp(s).getTime()),"yyyy-MM-dd HH:mm:ss") ,"yyyy-MM-dd HH:mm:ss");
        }
    }

    @Override
    public Date getResult(ResultSet resultSet, int i) throws SQLException {
        log.info("getResult");
        return new Date(resultSet.getLong(i));
    }

    @Override
    public Date getResult(CallableStatement callableStatement, int i) throws SQLException {
        log.info("getResult");
        return callableStatement.getDate(i);
    }
}
